<template>
<div class="askforinvoicetothefactory">
  <div class="head">
    <div class="btns clearfix">
      <h2>增值税开票信息</h2>
      <!-- <el-button class="export"  :disabled="!editable" type="primary">导出</el-button> -->
    </div>


    <div class="invoice">
      <div class="invoice-title">
        <h3>公 司 名 称 ：天津金贸链进出口有限公司</h3>
        <h3>纳税人识别号：91120118MA05K8NK2E</h3>
        <h3> 地 址：天津自贸试验区（空港经济区）环河南路88号2-2205号</h3>
        <h3>电 话：010-50911255</h3>
        <h3>开 户 银 行 ：中信银行股份有限公司天津自由贸易试验区分行</h3>
        <h3>银 行 账 户 ：8111401011700147295</h3>
        <el-row class="invoice-title__input">
          <el-col :span="3"><h3>收 件 人：</h3></el-col>
          <el-col :span="16">
            <el-input v-model="data.documentprocess_aski_receiver" placeholder="请输入收件人名称"></el-input>
          </el-col>
        </el-row>
        <el-row  class="invoice-title__input">
          <el-col :span="3"><h3>邮 政 编 码：</h3></el-col>
          <el-col :span="16">
            <el-input v-model="data.documentprocess_aski_addressCode" placeholder="请输入收件人邮政编码"></el-input>
          </el-col>
        </el-row>
        <el-row   class="invoice-title__input">
          <el-col :span="3"><h3>邮寄地址：</h3></el-col>
          <el-col :span="16">
            <el-input v-model="data.documentprocess_aski_address" placeholder="请输入收件人邮寄地址"></el-input>
          </el-col>
        </el-row>
      </div>

      <div class="invoice-table">
        <h3>开票内容</h3>

        <el-table :data="tableData" border style="width: 100%">

          <el-table-column type="index" label="序号" :index="indexMethod"></el-table-column>
          <el-table-column prop="documentprocess_aski_producuts" label="产品" width="180">
            <template slot-scope="scope">
                      <el-input :readonly="!editable" v-model="scope.row.documentprocess_aski_producuts" ></el-input>
                  </template>
          </el-table-column>
          <el-table-column prop="documentprocess_aski_description" label="规格型号">
            <template slot-scope="scope">
                      <el-input :readonly="!editable" v-model="scope.row.documentprocess_aski_description" ></el-input>
                  </template>
          </el-table-column>

          <el-table-column prop="documentprocess_aski_price" label="单价" >
            <template slot-scope="scope">
                      <!-- <input type="number" :min="0" :step="0.1" :disabled="!editable" @input="handleTableNumberChange" v-model="scope.row.documentprocess_aski_price" /> -->
                      <el-input-number :disabled="!editable" @change="handleTableNumberChange" type="number" :controls="false" v-model="scope.row.documentprocess_aski_price" ></el-input-number>
                  </template>
          </el-table-column>

          <el-table-column prop="documentprocess_aski_quantity" label="数量">
            <template slot-scope="scope">
                      <el-input-number :disabled="!editable" @change="handleTableNumberChange" type="number" :controls="false" v-model="scope.row.documentprocess_aski_quantity" ></el-input-number>
                  </template>
          </el-table-column>




          <el-table-column prop="documentprocess_aski_unit" label="单位">
            <template slot-scope="scope">
                      <el-input :readonly="!editable" v-model="scope.row.documentprocess_aski_unit" ></el-input>
                  </template>
          </el-table-column>
          <el-table-column prop="documentprocess_aski_lineAmount" label="总价">
            <template slot-scope="scope">
                      <input :disabled="!editable" type="number"  v-model="scope.row.documentprocess_aski_lineAmount" />
                  </template>
          </el-table-column>

          <el-table-column label="操作" width="100" v-if="editable">
            <template slot-scope="scope">
            <el-button @click="addNewLine(scope.$index, data.documentprocess_aski_table)" type="text" size="small">添加</el-button>
            <el-button @click="removeCurrentLine(scope.$index, data.documentprocess_aski_table)" type="text" size="small">移除</el-button>
          </template>
          </el-table-column>
        </el-table>
      </div>
    </div>


    <div class="upload">
      <p class="upload-hint">票据/附件</p>
      <div>
        <div class="upload-btn">
          <input type="file"  v-show="editable"  name="file" multiple @change="selectFiles">
          <el-button :disabled="!editable" type="primary">选择附件</el-button>
        </div>

        <ul class="upload-files">
          <li @mouseover="handleOver(item)" :key="index"  @mouseout="handleOut(item)" v-for="(item,index) in data.attachedFiles">
            <span @click="download(item.id, $event)">{{item.name}}</span>
            <span v-if="editable && item.status" class="el-icon-circle-check" style="color:#67c23a;"></span>
            <span v-else-if="editable" class="el-icon-circle-close" @click="changeFiles(index,item)" style="color:red;"></span>
          </li>
        </ul>
      </div>
    </div>
  </div>


</div>
</template>

<script>
import { uploadFiles } from "@/server/initiatingprocess";
import { filedownload, deleteFile } from "@/server/customermanagement/index.js";
import {
  getData,
  getSendMenus,
  getOrderNumber
} from "@/server/initiatingprocess";

import { getStore, setStore, removeStore } from "@/assets/js/common.js";
import {toFixed} from '@/util/transform.js';

export default {
  created() {
    let form = _.cloneDeep(
      this.relatedData.documentprocess_cc_declarationForm
        .documentprocess_cc_df_table
    );
    let current = this.data.documentprocess_aski_table;


    for (let i = 0; i < form.length; i++) {
      if (!current[i]) {
        current.push({
          documentprocess_aski_producuts: "",
          documentprocess_aski_description: "",
          documentprocess_aski_price: "",
          documentprocess_aski_quantity: "",
          documentprocess_aski_unit: "",
          documentprocess_aski_lineAmount: ""
        });
      }

      let productName = form[i].documentprocess_cc_df_productName;
      let productDesc  = form[i].documentprocess_cc_df_productDesc;

      let qaw = form[i].documentprocess_cc_df_quantityAndUnit
        .toString()
        .split(",");

      current[i].documentprocess_aski_producuts = productName;
      current[i].documentprocess_aski_description = productDesc;
      current[i].documentprocess_aski_price =
        toFixed(form[i].documentprocess_cc_df_price, 2);
      current[i].documentprocess_aski_quantity = parseInt(qaw[0]);
      current[i].documentprocess_aski_unit = qaw[1];
      current[i].documentprocess_aski_lineAmount =
        toFixed(form[i].documentprocess_cc_df_amount, 2);
    }
  },
  updated() {
    
  /*
    //?????????????
    // if (getStore("documentprocess") && !this.relation) {

    //   let formInstId = getStore("formInstId");
      
    //   let dtcData;
    //   getData({
    //     formInstId: formInstId,
    //     formServiceName: "business_lading"
    //   }).then(response => {
    //     let data = response.data.datas[0];
    //     dtcData = data.businessform_domestictradecontract[0];

    //     let dtcDataLen = dtcData.bd_table1.length;

    //     let documentprocess = JSON.parse(getStore("documentprocess"));

    //     let form = _.cloneDeep(
    //       documentprocess.documentprocess_cc.documentprocess_cc_declarationForm
    //         .documentprocess_cc_df_table
    //     );



    //     let formLen = form.length;

    //     if (dtcDataLen < formLen) {
    //       form.splice(dtcDataLen);
    //     }

    //     let current = this.data.documentprocess_aski_table;



    //     for (let i = 0; i < form.length; i++) {
    //       if (!current[i]) {
    //         current.push({
    //           documentprocess_aski_producuts: "",
    //           documentprocess_aski_description: "",
    //           documentprocess_aski_price: "",
    //           documentprocess_aski_quantity: "",
    //           documentprocess_aski_unit: "",
    //           documentprocess_aski_lineAmount: ""
    //         });
    //       }

    //       let desc = form[i].documentprocess_cc_df_prodAndDesc
    //         .toString()
    //         .split(",");
    //       let qaw = form[i].documentprocess_cc_df_quaAndWeight
    //         .toString()
    //         .split(",");

    //       current[i].documentprocess_aski_producuts = desc[0];
    //       current[i].documentprocess_aski_description = desc[1];
    //       // current[i].documentprocess_aski_price = form[i].documentprocess_cc_df_price;
    //       current[i].documentprocess_aski_price =
    //         toFixed(dtcData.bd_table1[i].bd_table1_price, 2);
    //       current[i].documentprocess_aski_quantity = parseInt(qaw[0]);
    //       current[i].documentprocess_aski_unit = qaw[1];
    //       current[i].documentprocess_aski_lineAmount =
    //         toFixed(form[i].documentprocess_cc_df_amount, 2);
    //     }

    //     removeStore("documentprocess");
    //   });
    // }

    // if (this.clickTimes == 1 && this.relation){
    //   let form = _.cloneDeep(this.relatedData.documentprocess_cc_declarationForm.documentprocess_cc_df_table);
    //   let current = this.data.documentprocess_aski_table;

    //   for (let i = 0; i < form.length; i++) {
    //     if (!current[i]) {
    //      current.push({
    //      documentprocess_aski_producuts :"",
    //      documentprocess_aski_description: "",
    //      documentprocess_aski_price : "",
    //      documentprocess_aski_quantity: "",
    //      documentprocess_aski_unit: "",
    //      documentprocess_aski_lineAmount: ""
    //     });
    //     }

    //     current[i].documentprocess_aski_producuts = (form[i].documentprocess_cc_df_prodAndDesc)[0];
    //     current[i].documentprocess_aski_description = (form[i].documentprocess_cc_df_prodAndDesc)[1];
    //     current[i].documentprocess_aski_price = form[i].documentprocess_cc_df_price;
    //     current[i].documentprocess_aski_quantity = (form[i].documentprocess_cc_df_quaAndWeight)[0];
    //     current[i].documentprocess_aski_unit = (form[i].documentprocess_cc_df_quaAndWeight)[1];
    //     current[i].documentprocess_aski_lineAmount = form[i].documentprocess_cc_df_amount;
    //   }
    //   this.clickTimes = 2;
    //   this.$forceUpdate();
    // }
  */

    if (this.clickTimes ==1) {

        let flag = this.data.modifyTime ? true : false;

          let innerFlag = this.data.documentprocess_aski_table.findIndex(item => {
            return  item.modifyTime != null;
          }) == -1 ? false : true;

          flag  = flag || innerFlag;

        if (!flag) {
          let form = _.cloneDeep(
            this.relatedData.documentprocess_cc_declarationForm
              .documentprocess_cc_df_table
          );
          let current = this.data.documentprocess_aski_table;

          for (let i = 0; i < form.length; i++) {
            if (!current[i]) {
              current.push({
                documentprocess_aski_producuts: "",
                documentprocess_aski_description: "",
                documentprocess_aski_price: "",
                documentprocess_aski_quantity: "",
                documentprocess_aski_unit: "",
                documentprocess_aski_lineAmount: ""
              });
            }

            
          let productName = form[i].documentprocess_cc_df_productName;
          let productDesc  = form[i].documentprocess_cc_df_productDesc;

          let qaw = form[i].documentprocess_cc_df_quantityAndUnit
            .toString()
            .split(",");

            current[i].documentprocess_aski_producuts =  productName;
            current[i].documentprocess_aski_description = productDesc;
            current[i].documentprocess_aski_price =
              toFixed(form[i].documentprocess_cc_df_price, 2);
            current[i].documentprocess_aski_quantity = parseInt(qaw[0]);
            current[i].documentprocess_aski_unit = qaw[1];
            current[i].documentprocess_aski_lineAmount =
              toFixed(form[i].documentprocess_cc_df_amount, 2);
          }
        }

        this.clickTimes = 2;
    }

    this.updateTable();
  },
  methods: {
    indexMethod(value) {
      return value + 1;
    },
    selectFiles(event) {
      //票据附件
      let _this = this;

      //直接上传，并且获得后端返回的文件的url,将url保存到 this.data.attachedFiles中
      uploadFiles(event.target.files).then(resArr => {
        resArr.forEach(function(res, i) {
          _this.data.attachedFiles.push({
            name: event.target.files[i].name,
            status: 1,
            id: res.data.datas[0].id
          });
        });

        _this.$forceUpdate();
      });
    },
    changeFiles(index, item) {
      deleteFile({ id: item.id }).then(res => {
        if (res.code != 1) {
          this.$message.error("删除失败，请检查网络后重试");
        } else {
          this.data.attachedFiles.splice(index, 1);
        }
      });
    },
    handleOver(item) {
      item.status = 0;
      this.$forceUpdate();
    },
    handleOut(item) {
      item.status = 1;
      this.$forceUpdate();
    },
    download(id, event) {
      window.open("http://47.104.93.41/api/common/download?id=" + id);
    },
    addNewLine(currentIndex, table) {
      let newLine = _.cloneDeep(table[currentIndex]);
      _.unset(newLine, 'askId');
      _.unset(newLine, 'createTime');
      _.unset(newLine, 'formInstId');
      _.unset(newLine, 'id');
      _.unset(newLine, 'modifyTime');

      // for (let prop in newLine) {
      //   newLine[prop] = '';
      // }

      table.splice(currentIndex + 1, 0, newLine);
    },
    removeCurrentLine(currentIndex, table) {
      if (table.length > 1) {
        table.splice(currentIndex, 1);
      }
    },

    handleTableNumberChange() {
      this.updateTable();
      this.$forceUpdate();
    },

    updateTable() {
      let current = this.data.documentprocess_aski_table;

      for (let i = 0; i < current.length; i++) {
        current[i].documentprocess_aski_price = toFixed(current[i].documentprocess_aski_price, 2);

        current[i].documentprocess_aski_lineAmount = toFixed(
          current[i].documentprocess_aski_price *
          current[i].documentprocess_aski_quantity, 2);
      }
    },


    /**选择币种 */
    currencySel(name){
        return (h, {column, $index}) => {
        let self = this;
        return  h("div", {
          attrs: {
            class: "select-currency"
          }
        }, [
          h("span", name),
          h("select", {domProps: {
            value: self.currencyValue
          },
          on: {
            change: function(event){
              self.currencyValue = event.target.value;
              self.data.documentprocess_aski_currencyValue = event.target.value;
            }
          }
          },[
            h("option", "人民币"),
            h("option", "美元"),
            h("option", "加元"),
            h("option", "欧元"),
          ])
        ]);
      }
    },
  },
  computed: {
    tableData() {
      let current = this.data.documentprocess_aski_table;

      for (let i = 0; i < current.length; i++) {
        current[i].documentprocess_aski_lineAmount = toFixed(
          current[i].documentprocess_aski_price *
          current[i].documentprocess_aski_quantity, 2);
      }
      return current;
    }
  },
  data() {
    return {
      clickTimes: 0,
      currencyValue: '人民币',
    };
  },
  props: {
    data: {
      type: Object,
      required: true
    },
    relation: {
      type: Boolean,
      required: true
    },
    relatedData: {
      type: Object,
      required: true
    },
    editable: {
      type: Boolean,
      required: true
    }
  }
};
</script>

<style lang="scss">
.askforinvoicetothefactory {
  padding: 20px;


  .select-currency {
      select {
        margin-left: 12px;
        height: 30px;
        width: 60px;
      }
  }

  border: 1px solid #999;
  .head {
    .btns {
      width: 100%;
      height: 80px;
      text-align: center;
      .export {
        float: right;
      }
    }

    .invoice {
      .invoice-title {
        > h3 {
          padding: 15px 0;
          > p {
            padding: 15px 0;
          }
        }

        input {
          border: none;
        }

        .invoice-title__input {
          line-height: 40px;
        }
      }

      .invoice-table {
        > h3 {
          padding: 20px 0;
        }

        input {
              border: none;
              outline: none;
              background-color: transparent;
             height: 100%;
        }

        .el-table {
          margin-bottom: 20px;

          td {
            border: 1px solid #e6ebf5;
          }
        }

        .el-input__inner {
          border: none;
          background: transparent;
          padding: 0;
          text-align: center;
        }

        .el-input-number__decrease,
        .el-input-number__increase {
          width: 20px;

          border: none;
          background: transparent;
        }

        .el-input-number {
          width: 100%;
          min-width: 80px;
        }
      }
    }

    .upload {
      > div {
        border: 1px solid #999;
        padding: 20px 0 40px 20px;
      }

      .upload-btn {
        position: relative;
        > input {
          opacity: 0;
          width: 100px;
          height: 40px;
          position: absolute;
          top: 0;
          left: 0;
        }
      }

      .upload-files {
        > li {
          width: 300px;
          padding: 10px 0;
          transition: all 0.5s linear;

          &:hover {
            > span {
              color: #409eff;
            }
          }
        }

        font-size: 16px;
        span {
          padding: 0 10px;
          cursor: pointer;
          display: inline;
        }
        span.el-icon-close:hover {
          cursor: pointer;
        }
      }
      .upload-hint {
        font-size: 20px;
        margin-bottom: 10px;
      }
    }
  }
}
</style>
